<template>
  <div class="app-container calendar-list-container user-container">
    <div class="filter-container">
      <el-form>
        <el-row class="row-bg" justify="space-around" type="flex">
          <el-col :span="16">
            <el-form-item label="类别">
              <template>
                <el-select @change="onChange" placeholder="请选择" v-model="type" clearable>
                  <el-option
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    v-for="item in typeList">
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="临时">
              <template>
                <el-select @change="onChange" placeholder="请选择" v-model="temporary">
                  <el-option
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    v-for="item in displayList">
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0" class="cutOffLine">
          <div class="buttonGroup">
            <el-button @click="queryDataList" size="small" type="primary">
              <icon name="search"/>
              查询
            </el-button>
          </div>
        </el-row>
        <el-row :gutter="0" class="cutOffLine">
          <el-row justify="flex-start" type="flex">
            <el-button @click="enableEditDialog('ADD')" size="small" type="primary">
              <icon name="plus"/>
              新增
            </el-button>
            <el-button
              :disabled="currentSelectId == null"
              @click="enableEditDialog('COPY')"
              size="small"
              type="primary">
              <icon name="copy"/>
              复制
            </el-button>
            <el-button
              :disabled="currentSelectId == null"
              @click="del()"
              icon="el-icon-delete"
              size="small"
              type="primary">
              删除
            </el-button>
            <el-button
              :disabled="currentSelectId == null"
              @click="enableHistoryDialog(currentSelectId)"
              size="small"
              type="primary">
              <icon name="search"/>
              查看执行历史
            </el-button>
          </el-row>
        </el-row>
      </el-form>
    </div>
    <el-table
      :data="dataList"
      @current-change="handleCurrentChange"
      @row-dblclick="enableEditDialog('MODIFY')"
      border
      element-loading-background="rgba(0, 0, 0, 0.8)"
      element-loading-spinner="el-icon-loading"
      element-loading-text="拼命加载中"
      highlight-current-row
      ref="multipleTable"
      style="width: 100%"
      v-loading="loading">
      <el-table-column
        align="center"
        label='类别'
        width="90px">
        <template slot-scope="scope">
          <div>{{getDisplay(scope.row.type, typeList)}}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label='任务名称'
        prop="jobName"
        width="200px">
      </el-table-column>
      <el-table-column
        align="center"
        label='起始时间'
        prop="startTime"
        width="150px"
        v-if="type !== '1'">
      </el-table-column>
      <el-table-column
        align="center"
        label='cron表达式'
        prop="cron"
        width="150px"
        v-if="type === '1' || type == null">
      </el-table-column>
      <el-table-column
        align="center"
        label='周期(秒)'
        prop="period"
        width="100px"
        v-if="type === '2' || type === '3' || type == null">
      </el-table-column>
      <el-table-column
        align="center"
        label='重试次数'
        prop="retry"
        width="80px">
      </el-table-column>
      <el-table-column
        align="center"
        label='服务名称'
        prop="service"
        width="200px">
      </el-table-column>
      <el-table-column
        align="center"
        label='执行方法'
        prop="function"
        width="200px">
      </el-table-column>
      <el-table-column
        align="center"
        label='执行参数'
        prop="parameter"
        width="300px">
      </el-table-column>
      <el-table-column
        align="center"
        label='是否运行'
        width="80px">
        <template slot-scope="scope">
          <div>{{getDisplay(scope.row.status, displayList)}}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label='临时任务'
        width="80px">
        <template slot-scope="scope">
          <div>{{getDisplay(scope.row.temporary, displayList)}}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label='创建时间'
        prop="createAt"
        width="150px">
      </el-table-column>
      <el-table-column
        align="center"
        label='备注'
        prop="remark"
        width="300px">
      </el-table-column>
    </el-table>
    <el-row class="row-padding" justify="space-between" type="flex">
      <el-pagination :current-page="page.current" :page-size="page.size" :page-sizes="[10, 20, 30, 40, 50]"
                     :total="page.total" @current-change="handleCurrentPageChange" @size-change="handleSizeChange"
                     background layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </el-row>
    <el-dialog
      :title="editDialog.title"
      :visible.sync="editDialog.visible"
      @close="clearDialog(editDialog)">
      <el-row>
        <el-col :span="20">
          <el-form :model="editDialog.data" ref="editDialogForm">
            <el-form-item label="类别">
              <el-select
                clearable
                placeholder="选择类别"
                v-model="editDialog.data.type">
                <el-option
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  v-for="item in typeList">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="定时任务名称" prop="name">
              <el-input placeholder="任务名称" v-model="editDialog.data.jobName"/>
            </el-form-item>

            <el-form-item label="开始时间" v-if="editDialog.data.type !== '1'">
              <el-date-picker
                :picker-options="startPickerOptions"
                align="right"
                placeholder="开始时间"
                type="datetime"
                v-model="editDialog.data.startTime"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="运行周期" v-if="editDialog.data.type === '2' || editDialog.data.type === '3'">
              <el-input v-model="editDialog.data.period"/>
            </el-form-item>
            <el-form-item label="CRON表达式" v-if="editDialog.data.type === '1'">
              <el-input v-model="editDialog.data.cron"/>
            </el-form-item>

            <el-form-item label="重试次数">
              <el-input-number :step="1" label="次数" size="mini" v-model="editDialog.data.retry"/>
            </el-form-item>
            <el-form-item label="服务名称">
              <el-input v-model="editDialog.data.service"/>
            </el-form-item>
            <el-form-item label="方法名称">
              <el-input v-model="editDialog.data.function"/>
            </el-form-item>
            <el-form-item label="参数">
              <el-input v-model="editDialog.data.parameter"/>
            </el-form-item>

            <el-form-item label="是否运行">
              <el-select
                clearable
                placeholder="是否运行"
                v-model="editDialog.data.status">
                <el-option
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  v-for="item in displayList">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input autosize clearable placeholder="备注"
                        type="textarea" v-model="editDialog.data.remark"/>
            </el-form-item>

          </el-form>
        </el-col>
      </el-row>
      <span class="dialog-footer" slot="footer">
        <el-button @click="clearDialog(editDialog)">取 消</el-button>
        <el-button @click="update(editDialog.add)" type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      width="80%"
      :title="historyDialog.title"
      :visible.sync="historyDialog.visible"
      @close="clearDialog(historyDialog)">
      <el-form>
        <el-row class="row-bg historyCondition" justify="space-around" type="flex">
          <el-col :span="12">
            <el-form-item label="运行结果">
              <template>
                <el-select @change="onHistoryChange" placeholder="请选择" v-model="historyDialog.condition.result">
                  <el-option
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    v-for="item in historyDialog.resultList">
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="historyDialog.condition.timeRange"
                @change="onHistoryChange"
                type="datetimerange"
                align="right"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['08:00:00', '20:00:00']">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="historyDialog.data"
        border
        element-loading-background="rgba(0, 0, 0, 0.8)"
        element-loading-spinner="el-icon-loading"
        element-loading-text="拼命加载中"
        highlight-current-row
        ref="multipleTable"
        style="width: 100%"
        v-loading="loading">
        <el-table-column
          align="center"
          label='类别'
          width="90px">
          <template slot-scope="scope">
            <div>{{getDisplay(scope.row.type, typeList)}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label='任务名称'
          prop="jobName"
          width="200px">
        </el-table-column>
        <el-table-column
          align="center"
          label='执行参数'
          prop="parameter"
          width="300px">
        </el-table-column>
        <el-table-column
          align="center"
          label='运行结果'
          width="80px">
          <template slot-scope="scope">
            <div>{{getDisplay(scope.row.result, historyDialog.resultList)}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label='执行开始'
          width="200px"
          prop="runAt">
        </el-table-column>
        <el-table-column
          align="center"
          label='执行结束'
          width="200px"
          prop="finishAt">
        </el-table-column>
        <el-table-column
          align="center"
          label='起始时间'
          prop="startTime"
          width="150px"
          v-if="editDialog.data.type !== '1'">
        </el-table-column>
        <el-table-column
          align="center"
          label='cron表达式'
          prop="cron"
          width="150px"
          v-if="editDialog.data.type === '1'">
        </el-table-column>
        <el-table-column
          align="center"
          label='周期(秒)'
          prop="period"
          width="100px"
          v-if="editDialog.data.type === '2' || editDialog.data.type === '3'">
        </el-table-column>
      </el-table>
      <el-row class="row-padding" justify="space-between" type="flex">
        <el-pagination :current-page="historyDialog.page.current" :page-size="historyDialog.page.size"
                       :page-sizes="[10, 20, 30, 40, 50]"
                       :total="historyDialog.page.total" @current-change="handleHistoryCurrentPageChange"
                       @size-change="handleHistorySizeChange"
                       background layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      apiName: {
        querySchedule: this.apiType.sys.querySchedule,
        updateSchedule: this.apiType.sys.updateSchedule,
        deleteSchedule: this.apiType.sys.deleteSchedule,
        queryScheduleHistory: this.apiType.sys.queryScheduleHistory
      },
      type: null,
      typeList: [
        {
          label: '一次性',
          value: '0'
        },
        {
          label: 'CRON定时',
          value: '1'
        },
        {
          label: '定时任务',
          value: '2'
        },
        {
          label: '延迟周期',
          value: '3'
        }
      ],
      temporary: '0',
      displayList: [
        {
          label: '是',
          value: '1'
        },
        {
          label: '否',
          value: '0'
        }
      ],
      dataList: [],
      // 分页信息
      page: {
        total: 0,
        current: 1,
        size: 10
      },
      currentRow: {},
      currentSelectId: null,
      formLabelWidth: '100px',
      loading: false,
      startPickerOptions: {
        disabledDate: (time) => {
          return time.getTime() <= Date.now() - 8.64e7
        }
      },
      editDialog: {
        title: '',
        visible: false,
        add: true,
        data: {
          id: '',
          jobName: '',
          type: null,
          cron: null,
          startTime: null,
          period: 0,
          retry: 0,
          service: null,
          function: null,
          parameter: null,
          status: '1',
          remark: ''
        },
        defaultData: {
          id: '',
          jobName: '',
          type: null,
          cron: null,
          startTime: null,
          period: 0,
          retry: 0,
          service: null,
          function: null,
          parameter: null,
          status: '1',
          remark: ''
        }
      },
      historyDialog: {
        scheduleId: '',
        title: '执行历史',
        visible: false,
        data: [],
        condition: {
          result: null,
          timeRange: []
        },
        resultList: [
          {
            label: '成功',
            value: '1'
          },
          {
            label: '失败',
            value: '0'
          }
        ],
        page: {
          total: 0,
          current: 1,
          size: 10
        },
        timeRange: {}
      }
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.resultData = undefined
      this.page = {
        total: 0,
        current: 1,
        size: 20
      }
      this.loading = false
      this.queryDataList()
    },
    handleCurrentPageChange (val) {
      this.page.current = val
      this.queryDataList()
    },
    handleSizeChange (val) {
      this.page.size = val
      this.queryDataList()
    },
    queryDataList () {
      const _this = this
      const body = {
        type: _this.type,
        temporary: _this.temporary,
        currentPage: _this.page.current,
        pageSize: _this.page.size
      }
      _this.fetch(this.apiName.querySchedule, null, body, function (responseData) {
        _this.dataList = responseData.data.info
        _this.page.total = parseInt(responseData.data.totalSize)
      }, null, false)
    },
    enableEditDialog (type) {
      if (type === 'ADD') {
        this.editDialog.add = true
        this.editDialog.title = '新增定时任务'
        this.editDialog.data = this.editDialog.defaultData
      } else if (type === 'MODIFY') {
        this.editDialog.add = false
        this.editDialog.title = '变更定时任务'
        this.editDialog.data = {}
        this.editDialog.data = {
          ...this.currentRow
        }
      } else if (type === 'COPY') {
        this.editDialog.add = true
        this.editDialog.title = '复制定时任务'
        this.editDialog.data = {}
        this.editDialog.data = {
          ...this.currentRow
        }
      }
      this.editDialog.visible = true
    },
    update (addAble) {
      if (addAble) {
        this.editDialog.data.id = null
      }
      const _this = this
      const body = {
        ...this.editDialog.data
      }
      _this.fetch(this.apiName.updateSchedule, null, body, function () {
        _this.init()
        _this.clearDialog(_this.editDialog)
      }, null, false)
    },
    del () {
      const _this = this
      this.$confirm('删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const body = {
          id: this.currentSelectId
        }
        _this.fetch(this.apiName.deleteSchedule, null, body, function () {
          _this.init()
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }, null, false)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    clearDialog (dialog) {
      dialog.visible = false
    },
    handleCurrentChange (currentRow, oldCurrentRow) {
      this.currentRow = currentRow
      this.currentSelectId = currentRow.id
    },
    onChange () {
      this.queryDataList()
    },
    enableHistoryDialog (id) {
      this.historyDialog.visible = true
      this.historyDialog.scheduleId = id
      this.historyDialog.data = []
      this.queryScheduleHistory()
    },
    queryScheduleHistory () {
      const _this = this
      const body = {
        result: this.historyDialog.condition.result,
        startAt: this.formatDate(_this.historyDialog.condition.timeRange[0]),
        endAt: this.formatDate(_this.historyDialog.condition.timeRange[1]),
        scheduleId: _this.historyDialog.scheduleId,
        currentPage: _this.historyDialog.page.current,
        pageSize: _this.historyDialog.page.size
      }
      _this.fetch(this.apiName.queryScheduleHistory, null, body, function (responseData) {
        _this.historyDialog.data = responseData.data.info
        _this.historyDialog.page.total = parseInt(responseData.data.totalSize)
      }, null, false)
    },
    handleHistoryCurrentPageChange (val) {
      this.historyDialog.data.current = val
      this.queryScheduleHistory()
    },
    handleHistorySizeChange (val) {
      this.page.size = val
      this.queryScheduleHistory()
    },
    onHistoryChange () {
      this.queryScheduleHistory()
    }
  }
}
</script>

<style>
  .historyCondition {
    margin-bottom: 10px
  }

  .historyCondition .el-input__inner {
    height: 36px
  }

  .historyCondition .el-form-item__label {
    line-height: 27px
  }
</style>
